<?php

require_once('/home/wwwroot/staylife_server/app/conf/product/mailer.php');
require_once('/home/wwwroot/staylife_server/system/Third/PHPMailer/class.phpmailer.php');
const WEBHOOK_TOKEN = 'more_staylife_wiki';

// 拉取代码
echo shell_exec('cd ' . __DIR__ . ' && /usr/bin/git pull origin master 2>&1');

// 接受推送数据
$postData = file_get_contents('php://input');

// 记录日志
file_put_contents('/home/wwwlogs/wiki_git_hooks.log', $postData, FILE_APPEND);

$postData = json_decode($postData, true);

if (WEBHOOK_TOKEN !== $postData['token']) {
    return false;
}

$subject = "{$postData['repository']['name']} 变更: " . $postData['commits'][0]['short_message'];

$html = '';

foreach ($postData['commits'] as $key => $value) {

    // 如果commit message中含有'@dev',则给研发组所有人发送邮件通知
    if (strpos($postData['commits'][$key]['short_message'], '@dev') === false) {
        continue;
    }

    $html .= "Morecruit@葬爱" . mt_rand(1, 6) . "少:{$postData['commits'][$key]['committer']['name']}" .
        "对项目{$postData['repository']['name']}进行了{$postData['event']}操作.<br/>" .
        "Comment: {$postData['commits'][$key]['short_message']}.<br/>" .
        "<a href='{$postData['commits'][0]['web_url']}'>查看详情</a>";

    $html .= '<hr/>';
}

// 如果不需要推送给成员,中断操作
if (! $html) {
    exit();
}

// 追加上git diff详情
$diffArr = [];
exec('git diff ' . $postData['before'] . ' ' . $postData['after'], $diffArr);

// 给diff的行变换颜色
foreach ($diffArr as $value) {
    if (preg_match('/^\-.*$/', $value)) {
        $html .= '<div style="color:red;">' . $value . '</div>';
    } elseif (preg_match('/^\+.*$/', $value)) {
        $html .= '<div style="color:green;">' . $value . '</div>';
    } else {
        $html .= $value . '<br/>';
    }
}

$recMail = [
    'dev@morecruit.cn',
];

$mail = new PHPMailer();

$mail->CharSet  = 'UTF-8';
$mail->Encoding = 'base64';

$mail->IsSMTP();
$mail->SMTPAuth  = true;
$mail->SMTPDebug = false;
$mail->Host      = PHP_MAILER_SMTP_HOST;
$mail->Username  = PHP_MAILER_SMTP_USER;
$mail->Password  = PHP_MAILER_SMTP_PWD;
$mail->From      = PHP_MAILER_NOREPLY_USER;
$mail->FromName  = 'noreply';

// 指定收件人
foreach ($recMail as $email) {
    $mail->AddAddress($email);
}

$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body    = $html;
$mail->Send();

